package com.xbx.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xbx.eduservice.entity.EduSubject;
import com.xbx.eduservice.entity.excel.SubjectData;
import com.xbx.eduservice.service.EduSubjectService;

import java.util.Map;


public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public EduSubjectService eduSubjectService;

    public SubjectExcelListener() {
    }
    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        System.out.println(subjectData.getOneSubjectName() +"<===>"+subjectData.getTwoSubjectName());
        //先判断一级分类
        //判断一级分类是否重复,匹配pid=0且字段名已经存在的edusubject，如果匹配到的话，取出该object的id值，并向其添加后续的二级数据。
        EduSubject existOneEduSubject = this.existOne(eduSubjectService, subjectData.getOneSubjectName());
        if (existOneEduSubject == null) {//没有相同的
            existOneEduSubject = new EduSubject();
            System.out.println("正在设置一级目录的pid与title");
            existOneEduSubject.setParentId("0");
            existOneEduSubject.setTitle(subjectData.getOneSubjectName());
            System.out.println("设置完毕");
            eduSubjectService.save(existOneEduSubject);
            System.out.println("已成功装入数据库");
        }
        //判断二级分类
        //取出一级分类中查找获取出的id值，二级分类分支的id判断条件，判断二级分类名称是否属于统一分支或者名称是否相同
        String pid = existOneEduSubject.getId();
        EduSubject existTwoEduSubject = this.existTwo(eduSubjectService, subjectData.getTwoSubjectName(), pid);
        if (existTwoEduSubject == null) {
            //给二级分类设置设置一级归类的id
            existTwoEduSubject = new EduSubject();
            existTwoEduSubject.setParentId(pid);
            existTwoEduSubject.setTitle(subjectData.getTwoSubjectName());
            eduSubjectService.save(existTwoEduSubject);
        }
    }
    public void invokeHeadMap(Map<Integer,String> headMap, AnalysisContext context) {
        System.out.println("表头信息"+headMap);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
    public EduSubject existOne(EduSubjectService eduSubjectService, String name) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", 0);
        wrapper.eq("title", name);
        EduSubject eduSubject = eduSubjectService.getOne(wrapper);
        return eduSubject;
    }

    public EduSubject existTwo(EduSubjectService eduSubjectService, String name, String pid) {
        //判断二级分类是否重复
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", pid);
        wrapper.eq("title", name);
        EduSubject twoeduSubject = eduSubjectService.getOne(wrapper);
        return twoeduSubject;
    }

}
